// 主题 + 语言包 + 路由
// App.tsx
import { ConfigProvider, theme, Watermark} from "antd";
// 国际化
import "dayjs/locale/zh-cn";
import { RouterProvider } from "react-router-dom";
import { routes } from "./router";
import { useState, useEffect } from "react";
import { antdLocales } from "@/i18n/config";


// defaultAlgorithm: 默认亮色主题算法
// darkAlgorithm: 暗色主题算法
// compactAlgorithm: 紧凑布局算法
// 定义主题配置类型
type ThemeConfig = {
  isDark: boolean;
  isCompact: boolean;
  lang: keyof typeof antdLocales;
};
const setAttributes = (theme: string) => {
  const html = document.documentElement;
  html.setAttribute("data-theme", theme);
};
// 获取 localStorage 中的主题配置
const getDefaultTheme = (): ThemeConfig => {
  if (typeof window === "undefined") {
    return { isDark: false, isCompact: false, lang: "zh" };
  }
  try {
    const saved = localStorage.getItem("theme");
    let theme = JSON.parse(saved)?.isDark ? "dark" : "light";
    setAttributes(theme);
    return JSON.parse(
      saved! ?? { isDark: false, isCompact: false, lang: "zh" }
    );
  } catch (error) {
    return { isDark: false, isCompact: false, lang: "zh" };
  }
};
// 实现主题切换
const App = () => {
  // 初始化时从 localStorage 读取配置
  const [themeConfig, setThemeConfig] = useState<ThemeConfig>(getDefaultTheme);
  const [account, setAccount] = useState<any>(()=>{
    let obj = JSON.parse(localStorage.getItem('token') || '{}')
    return obj?.username || 'Ant-Design-React'
  });
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "theme") {
        try {
          const newConfig = e.newValue ? JSON.parse(e.newValue) : null;
          newConfig && setThemeConfig(newConfig);
          setAttributes(newConfig?.isDark ? "dark" : "light");
        } catch (error) {
          console.error("主题配置解析失败", error);
        }
      }
      setAccount(JSON.parse(localStorage.getItem('token') || '{}')?.username || 'Ant-Design-React')
    };
    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);
  return (
    <ConfigProvider
      locale={antdLocales[themeConfig.lang]}
      theme={{
        algorithm: [
          themeConfig.isDark ? theme.darkAlgorithm : theme.defaultAlgorithm,
          ...(themeConfig.isCompact ? [theme.compactAlgorithm] : []),
        ],
        token: {
          colorPrimary: "#EC6303", // 可在此扩展自定义 token
          borderRadius: 2,
        },
        components: {
          Layout: {
            triggerHeight: themeConfig.isCompact ? 36 : 40, // 侧边栏折叠按钮高度和footer的高度不一致，所以强制修改
          },
        },
      }}
    >
      <Watermark content={account}>
        <RouterProvider router={routes} />
      </Watermark>
    </ConfigProvider>
  );
};

export default App;
